{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from image_function import *"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. Read data from the 'crop' folder\n",
    "2. label it with mouse click\n",
    "3. save the label field to the 'label' folder and the corresponding image field to the 'label_ori' folder"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_dir = 'Data\\\\sample3\\\\' # image folder"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# mouse callback function\n",
    "def draw_circle(event,x,y,flags,param):\n",
    "    global ix,iy,drawing, mode\n",
    "\n",
    "    if event == cv2.EVENT_LBUTTONDOWN: # press the buttom\n",
    "        drawing = True\n",
    "        ix,iy = x,y\n",
    "\n",
    "    elif event == cv2.EVENT_MOUSEMOVE:\n",
    "        if drawing == True:\n",
    "            if mode == 'R':\n",
    "                cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),-1) # green rectangel with drag\n",
    "                ROI_rec.append((ix,iy,x,y))\n",
    "\n",
    "            else:\n",
    "                \n",
    "                cv2.circle(img,(x,y),5,(0,0,255),-1) # red circle without drag\n",
    "                Cir_rec.append((x,y))\n",
    "\n",
    "    elif event == cv2.EVENT_LBUTTONUP: # release the buttom\n",
    "        drawing = False\n",
    "        if mode == 'R':\n",
    "            cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),1) # -1 is solid fill\n",
    "            ROI_rec.append((ix,iy,x,y))\n",
    "        else:\n",
    "            cv2.circle(img,(x,y),5,(0,0,255),-1)\n",
    "            Cir_rec.append((x,y))\n",
    "            \n",
    "            \n",
    "def draw_new_image(ROI_rec, Cir_rec, img_size):\n",
    "    #cv2.namedWindow('new_image')\n",
    "    img = np.zeros((img_size[0],img_size[1],3), np.uint8)\n",
    "    #cv2.imshow('image',img)\n",
    "\n",
    "    for index, cor in enumerate(ROI_rec):\n",
    "        img = cv2.rectangle(img, (cor[0],cor[1]),(cor[2],cor[3]),(0,255,0), -1) # 1 is hollow\n",
    "        \n",
    "    for index, cor in enumerate(Cir_rec, 1):\n",
    "        img = cv2.circle(img,(cor[0],cor[1]),5,(0,0,255),-1)\n",
    "        \n",
    "    while (1):\n",
    "        cv2.imshow('image',img)\n",
    "        k = cv2.waitKey(1) & 0xFF\n",
    "        if k == 27: ## wait for esc key to exit\n",
    "            break\n",
    "    cv2.destroyAllWindows()\n",
    "    return(img)\n",
    "\n",
    "def draw_label(img):\n",
    "    #img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)\n",
    "    img_size = np.shape(img)\n",
    "    cv2.namedWindow('image')\n",
    "    cv2.setMouseCallback('image',draw_circle)\n",
    "   \n",
    "    while(1):\n",
    "        cv2.imshow('image',img)\n",
    "        k = cv2.waitKey(1) & 0xFF\n",
    "        if k == ord('R'):\n",
    "            print ('select R')\n",
    "            mode = 'R'\n",
    "        elif k == ord('C'):\n",
    "            print ('select C')\n",
    "\n",
    "            mode = 'C'\n",
    "        elif k == 27: ## wait for esc key to exit\n",
    "            break\n",
    "        elif k == ord('d'): # keyboard press d to delete the last selection\n",
    "            if mode == 'R': # rect mode\n",
    "                ROI_rec.pop()\n",
    "            else:\n",
    "                Cir_rec.pop()\n",
    "\n",
    "\n",
    "    cv2.destroyAllWindows()\n",
    "\n",
    "    label = draw_new_image(ROI_rec, Cir_rec, img_size)\n",
    "    \n",
    "    return(label)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# read data and create folders to store labelled data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(832, 256, 256)"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data, fs = load_images_from_folder(data_dir + '\\\\crop') # load data\n",
    "np.shape(data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "global ROI_rec \n",
    "global Cir_rec\n",
    "global mode\n",
    "mode = 'C'\n",
    "drawing = False # true if mouse is pressed\n",
    "ix,iy = -1,-1\n",
    "\n",
    "ROI_rec = [] # record the coordinate of the rectangels\n",
    "Cir_rec = [] # record the coordinate of the circles"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "path_label = data_dir+'label\\\\' # path to store label\n",
    "path_image = data_dir+'label_ori\\\\' # path to store original image that correspond to the label\n",
    "\n",
    "ensure_dir(path_label) # create a folder to store the labelled images\n",
    "ensure_dir(path_image) # create a folder to store the labelled images"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "img_size = np.shape(data)\n",
    "st = np.asarray(round(img_size[0]/2) - 5) # starting training set\n",
    "fin = np.asarray(round(img_size[0]/2) + 5) # end of training set\n",
    "\n",
    "data_img = data[st:fin,:,:] # original image used for labelling"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i2, i in enumerate(range(st, fin)):    \n",
    "    ROI_rec = [] # record the coordinate of the rectangels\n",
    "    Cir_rec = [] # record the coordinate of the circles\n",
    "    \n",
    "    img = np.copy(data[i,:,:])\n",
    "    img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) \n",
    "    \n",
    "    label = draw_label(img)\n",
    "    \n",
    "    imageio.imwrite(path_label+str(i)+'.jpg', label[:,:,2])# only keep the red channel\n",
    "    imageio.imwrite(path_image+str(i)+'.jpg', (data[i,:,:])) \n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
